const app = getApp();
import { getStorage, setStorage } from "../../utils/localStorage.js";
import { baseUrl } from "../../api/request";
import { getMapDistance } from "../../utils/address"
import { routeRecomtion_List, routeLikes, intelPlaning_List, intelPlaning_Record, znRoute_Delete } from "../../api/luxian.js";

Component({
  properties: {},
  data: {
    //图片地址
    baseUrl: baseUrl,
    //用户所在位置经纬度
    latlng: {},
    //自定义导航栏组件参数
    navData: {
      title: '',
      level: 5
    },
    scrollTop: 0,
    //页面自定义导航栏高度
    pageTop: app.globalData.navHeight + 10,
    //页面类型索引
    pageIndex: 0,
    //线路推荐
    lineNav: [
      {
        title: '推荐',
        id: 1
      },
      {
        title: '周末',
        id: 2
      },
      {
        title: '亲子',
        id: 3
      },
      {
        title: '节气',
        id: 4
      },
      {
        title: '摄影',
        id: 5
      },
      {
        title: '网红',
        id: 6
      },
      {
        title: '历史文化',
        id: 7
      }
    ],
    lineNavIndex: 0,
    lineNavHeight: 80,
    lineNavState: false,
    lineTitleState: false,
    //列表搜索条件
    listQuery: {
      pageNum: 1,
      pageSize: 5,
      userId: null,
      dictValue: ""
    },
    //下拉刷新状态
    downState: false,
    //列表总数量
    total: 0,
    //线路规划列表
    routeRetionList: [],
    //智能规划列表
    IntelPlaningList: [],
    //智能规划记录数据
    inpngRecord: {},
    //路线类型列表
    routeTypeList: [],

  },
  lifetimes: {
    attached() {
      if(app.loginState()) return;
      this.setData({
        latlng: getStorage("latLng"),
        "listQuery.userId": getStorage("user").id,
      });
      this.getRouteTypeList();
      this.getRouteRecomtionList();
    },
    detached() { },
  },
  pageLifetimes: {
    show() {
      console.log(this.data.pageIndex, 'pageIndex');
      if (this.data.pageIndex == 1) {
        this.setData({
          pageIndex: this.data.IntelPlaningList.length === 0 ? 0 : 1
        });
        this.getIntelPlaningRecord();
      };
    },
  },
  methods: {
    //自定义导航栏切换点击事件
    lxNavEvent(e) {
      this.setData({
        pageIndex: e.detail,
        scrollTop: 0,
        "listQuery.pageNum": 1,
        "listQuery.pageSize": 5,
        total: 0,
        lineNavState: false,
      });
      if (this.data.pageIndex === 0) {
        this.setData({
          routeRetionList: []
        });
        this.getRouteRecomtionList();
      } else if (this.data.pageIndex === 1) {
        this.setData({ IntelPlaningList: [] });
        this.getIntelPlaningRecord();
        this.getIntelPlaningList();
      };
    },


    //乡镇列表点击事件
    townListTap(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/xaingcunDetail/index?id=' + item.villageId,
      });
    },

    /**
     *  线路推荐自定义方法
    */

    //获取线路规划列表
    getRouteRecomtionList() {
      routeRecomtion_List(this.data.listQuery).then(res => {
        res.data.rows.forEach(item => {
          item.image = item.image ? item.image.split(",") : [];
          item.lineTitleState = false;
        });
        this.setData({
          routeRetionList: [...this.data.routeRetionList, ...res.data.rows],
          total: Math.ceil(res.data.total / this.data.listQuery.pageSize)
        });
      });
    },

    //获取路线类型列表
    getRouteTypeList() {
      app.getDict("village_label").then(res => {
        res.data.unshift({ dictLabel: "全部", dictValue: "all" });
        const uniqueArray = res.data.filter((current, index, self) =>
          index === self.findIndex(item => item.dictLabel === current.dictLabel)
        );
        this.setData({ routeTypeList: uniqueArray });
      });
    },

    //类型切换框点击事件
    lineNavTap(e) {
      const index = e.currentTarget.dataset.index;
      let item = e.currentTarget.dataset.item;
      this.setData({
        lineNavIndex: index,
        "listQuery.dictValue": item.dictValue === "all" ? "" : item.dictValue,
        "listQuery.pageNum": 1,
        routeRetionList: [],
      });
      this.getRouteRecomtionList();
    },
    //nav右边箭头点击事件
    lineJtTap(e) {
      const state = e.currentTarget.dataset.state;
      this.setData({
        lineNavState: !state,
      });
    },
    //nav展开后右边箭头点击事件
    lineNavZkTap(e) {
      const state = e.currentTarget.dataset.state;
      this.setData({
        lineNavState: !state,
      });
    },
    //nav遮盖层列表点击事件
    lineNavTapzk(e) {
      const index = e.currentTarget.dataset.index,
        state = e.currentTarget.dataset.state;
      let item = e.currentTarget.dataset.item;
      this.setData({
        lineNavIndex: index,
        lineNavState: !state,
        "listQuery.dictValue": item.dictValue,
        "listQuery.pageNum": 1,
        routeRetionList: [],
      });
      this.getRouteRecomtionList();
    },
    //线路规划列表title点击事件
    lineTitleTap(e) {
      const state = e.currentTarget.dataset.state,
        index = e.currentTarget.dataset.index,
        lineTitleState = this.data.pageIndex === 0 ? "routeRetionList[" + index + "].lineTitleState" : "IntelPlaningList[" + index + "].lineTitleState";
      this.setData({
        [lineTitleState]: !state
      });
    },
    //线路推荐列表点赞按钮点击事件
    commentClick(e) {
      let that = this.data,
        item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        flag = !item.likeState ? true : false;
      routeLikes({ userId: that.listQuery.userId, travelId: item.travelId, state: flag }).then(res => {
        let state = this.data.pageIndex === 0 ? "routeRetionList[" + index + "].likeState" : "IntelPlaningList[" + index + "].likeState",
          num = this.data.pageIndex === 0 ? "routeRetionList[" + index + "].likeNumber" : "IntelPlaningList[" + index + "].likeNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
          });
        };
      });
    },
    //列表点击事件
    listTap(e) {
      const id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pagesLuxian/pages/detail/index?id=' + id,
      })
    },
    //导航按钮点击事件
    navigationTap(e) {
      const item = e.currentTarget.dataset.item;
      setStorage("pageId", "list");
      wx.navigateTo({
        url: '/pagesLuxian/pages/guihuaComplete/index?id=' + item.travelId,
      });
    },


    /**
     *  智能规划自定义方法
    */

    //获取历史规划记录数据
    getIntelPlaningRecord() {
      intelPlaning_Record({ userId: this.data.listQuery.userId }).then(res => {
        this.setData({
          inpngRecord: res.data.data
        });
      });
    },

    //获取智能规划列表
    getIntelPlaningList() {
      intelPlaning_List(this.data.listQuery).then(res => {
        res.data.rows.forEach(item => {
          item.image = item.image ? item.image.split(",") : [];
          item.lineTitleState = false;
        });
        this.setData({
          IntelPlaningList: [...this.data.IntelPlaningList, ...res.data.rows],
          total: Math.ceil(res.data.total / this.data.listQuery.pageSize)
        });
        if (this.data.IntelPlaningList.length === 0) {
          wx.navigateTo({
            url: '/pagesLuxian/pages/guiHua/index',
          });
        };
      });
    },

    //列表删除按钮点击事件
    znListDelete(e) {
      const item = e.currentTarget.dataset.item;
      wx.showModal({
        title: '删除警告',
        content: `请确认是否要删除路线名称为${item.title}的数据项`,
        complete: (res) => {
          if (res.confirm) {
            znRoute_Delete({ userId: this.data.listQuery.userId, travelId: item.travelId }).then(res => {
              wx.showToast({
                icon: 'none',
                title: res.data.msg,
                duration: 1000
              });
              setTimeout(() => {
                this.setData({
                  "listQuery.pageNum": 1,
                  IntelPlaningList: []
                });
                this.getIntelPlaningRecord();
                this.getIntelPlaningList();
              });
            });
          };
        }
      });
    },

    /* 图片放大功能 */
    imgTap(e) {
      const url = e.currentTarget.dataset.url,
        urlList = e.currentTarget.dataset.urllist;
      if (url) {
        const arr = urlList.map(item => this.data.baseUrl + item);
        app.imagePreview(url, arr);
      };
    },

    /* 上拉加载更多 */
    pullUp(e) {
      if ((this.data.listQuery.pageNum + 1) <= this.data.total) {
        this.setData({
          "listQuery.pageNum": this.data.listQuery.pageNum += 1
        });
        this.data.pageIndex === 0 ? this.getRouteRecomtionList() : this.getIntelPlaningList();
      };
    },
    /* 下拉刷新 */
    downUp() {
      this.setData({
        downState: true,
        "listQuery.pageNum": 1,
        "listQuery.pageSize": 5,
        routeRetionList: [],
        IntelPlaningList: [],
      });
      this.data.pageIndex === 0 ? this.getRouteRecomtionList() : this.getIntelPlaningRecord(); this.getIntelPlaningList();
      setTimeout(() => {
        wx.showToast({
          icon: 'none',
          title: '刷新成功',
          duration: 2000,
          mask: true,
        });
        this.setData({
          downState: false,
        });
      }, 2000)
    },
  }
})